'''# built_in'''
import os
import json

'''# custom'''
from common import PROJECTROOT


class init(object):

    def __repr__(self) -> str:
        return "窗口初始化事件类"
    
    def __init__(self) -> None:
        return

    def __call__(self, eel) -> None:
        @eel.expose
        def scan_clean(folderSrc):
            """
             对指定的“测试用例数据集”文件夹进行扫描清洗，生成对应的数据文件夹路径

             参数：
                @param folderSrc :   指定的“测试用例数据集”文件夹路径
            """
            informationDict = {}
            try:
                folderList = os.listdir(folderSrc)
                for folder in folderList:
                    folderIden = folder.split('_')[0]
                    informationDict[f'{folderIden.upper()}_FOLDER'] = f'{folderSrc}\\{folder}'
            except Exception as error:
                print(error)
                return False
            else:
                return {"CASES_FOLDER": informationDict['CASES_FOLDER']}

        @eel.expose
        def get_hierarchy(folderSrc, hierarchy):
            """
             获取指定文件夹的目录信息，并生成对应的目录结构数据

             参数：
                @param folderSrc :   指定的“用例步骤”文件夹路径
                @param hierarchy :   目录结构结果数组, 此处传入空数组 [] 即可
            """
            objectData = hierarchy  # 指向
            indexRoute = {}  # 数组索引关系路由
            for root, dirs, files in os.walk(folderSrc, topdown=True):
                root = format(root); dirs = eval(format(dirs)); files = eval(format(files))
                detailRoute = []  # 置空
                key_id = root.split('\\')[-1]

                '''路由进入'''
                try:
                    for index in indexRoute[key_id]: 
                        objectData = objectData[index]['children']
                    detailRoute = indexRoute[key_id]
                except Exception as error:
                    objectData.append({'id':key_id, 'label':key_id, 'children':[]})
                    objectData = objectData[0]['children']
                    detailRoute = [0]
                
                '''文件夹处理'''
                if dirs:
                    for num,folder in enumerate(dirs):
                        tran_Route = [item for item in detailRoute]
                        if os.listdir(root + '\\' + folder):
                            objectData.append({'id':folder, 'label':folder, 'children':[]})
                        else:
                            '''文件夹为空不可操作'''
                            objectData.append({'id':folder, 'label':folder, 'children':[], 'disabled': True})
                        tran_Route.append(num)
                        indexRoute[folder] = tran_Route
                
                '''文件处理'''
                if files:
                    for file in [item for item in files if ('xlsx' in item.split('.') or 'xls' in item.split('.'))]:
                        # 移除非excel工作簿文件
                        objectData.append({'id':file, 'label':file, 'file':root + '\\' + file})
                
                '''本级循环结束'''
                objectData = hierarchy  # 还原

            return hierarchy

        @eel.expose
        def get_path():
            """获取用例数据包路径"""
            try:
                with open(f'{PROJECTROOT}\\data\\cache\\path.json', 'r') as f:
                    jsonData = json.load(f)
                if jsonData['packagePath']:
                    return jsonData['packagePath'].replace('/', '\\')
                else:
                    raise Exception
            except Exception as error:
                print(error)
                return False

        @eel.expose
        def set_path(path):
            """
             设置用例数据包路径

             参数：
                @param path :   修改/设置的“用例数据包”路径
            """
            prices = {"packagePath": path.replace('/', '\\')}
            try:
                with open(f'{PROJECTROOT}\\data\\cache\\path.json', 'w') as f:
                    json.dump(prices, f)
                return path
            except Exception as error:
                print(error)
                return False